<template>
  <div class="dialog-role">
    <el-dialog
      :visible.sync="dialogVisible"
      :title="field"
      width="800px"
      @close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="dialog-ruleForm"
      >
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="ruleForm.roleName" clearable />
        </el-form-item>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <el-form-item
            label="字符权限:"
            prop="roleKey"
            style="flex: 1; margin: 0"
          >
            <el-input v-model="ruleForm.roleKey" clearable />
          </el-form-item>
          <div
            style="
              line-height: 18px;
              font-size: 12px;
              padding-left: 20px;
              color: rgba(0, 0, 0, 0.45);
            "
          >
            <div><i class="el-icon-info"></i>控制器中定义的权限字符</div>
            <div>如：@RequiresRoles("")</div>
          </div>
        </div>
        <el-form-item label="显示顺序:" prop="roleSort">
          <el-input v-model="ruleForm.roleSort" clearable />
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-switch v-model="ruleForm.status"> </el-switch>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="ruleForm.remark" clearable />
        </el-form-item>
        <el-form-item label="菜单权限:">
          <el-checkbox v-model="collapse">展开/折叠</el-checkbox>
          <el-checkbox v-model="checked">全选/不全选</el-checkbox>
          <el-checkbox v-model="checkStrictly">父子联动</el-checkbox>
        </el-form-item>
        <el-form-item label="">
          <div class="menu-permisssion">
            <el-tree
              ref="roleTree"
              :data="treeData"
              show-checkbox
              node-key="menuId"
              :default-expand-all="false"
              :expand-on-click-node="false"
              :default-checked-keys="menuIds"
              :check-strictly="!checkStrictly"
              @check="checkNodes"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <svg-icon
                  :icon-class="getNodeIcon(node)"
                  style="width: 16px; height: 14px"
                />
                <span>{{ node.label }}</span>
              </span>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  roleAdd,
  menuList,
  roleMenuTreeSelected,
  roleEdit,
} from "@/api/systemmanagement";

let id = 1000;
export default {
  name: "ProjectDetail",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    field: {
      type: String,
      default: "",
    },
    rowData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      ruleForm: {
        roleName: "",
        status: true,
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "请输入字符权限", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "请输入显示顺序", trigger: "blur" },
          {
            pattern: /^([1-9][0-9]{0,8}|0)(\.[0-9]{1,2})?$/,
            message: "请输入有效的数字",
            trigger: "blur",
          },
        ],
      },
      treeData: [],
      menuIds: [],
      checkStrictly: true,
      collapse: false,
      checked: false,
    };
  },
  computed: {
    dialogVisible: {
      get() {
        this.initType();
        return this.value; // 返回父组件通过 v-model 传递的值
      },
      set(val) {
        this.ruleForm = {};
        this.menuIds = [];
        this.collapse = false;
        this.checkStrictly = true;
        this.checked = false;

        this.$emit("close", val); // 当 dialogVisible 变化时，通知父组件更新
      },
    },
  },
  watch: {
    collapse(val) {
      // 当 collapse 值变化时，控制所有节点展开或折叠
      this.handleCollapseChange(val);
    },
    checked(val) {
      // 新增: 监听 checked 值变化
      this.handleCheckedChange(val);
    },
  },
  mounted() {
    this.initTree();
  },
  methods: {
    submitConfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submit();
        } else {
          return false;
        }
      });
    },
    submit() {
      let data = {
        roleName: this.ruleForm.roleName,
        roleKey: this.ruleForm.roleKey,
        roleSort: this.ruleForm.roleSort,
        status: this.ruleForm.status ? "0" : "1",
        remark: this.ruleForm.remark,
        menuIds: this.menuIds,
      };
      if (this.field == "添加角色") {
        roleAdd(data).then((res) => {
          if (res.code == 0) {
            this.$message.success(res.msg);
            this.dialogVisible = false;
            this.$emit("refresh");
          } else {
            this.$message.error(res.msg);
          }
        });
      } else {
        data.roleId = this.ruleForm.roleId;
        roleEdit(data).then((res) => {
          if (res.code == 0) {
            this.$message.success(res.msg);
            this.dialogVisible = false;
            this.$emit("refresh");
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },
    initTree() {
      menuList().then((res) => {
        this.treeData = this.processTreeData(res.data);
      });
    },
    initType() {
      if (this.field == "修改角色" && this.rowData.roleId) {
        this.ruleForm = { ...this.rowData };
        this.ruleForm.status = this.ruleForm.status == "1" ? false : true;
        this.getSelectedNode(this.ruleForm.roleId);
      } else {
        // 新增角色时初始化空表单
        this.ruleForm = {
          roleName: "",
          roleKey: "",
          roleSort: "",
          status: true,
          remark: "",
        };
        this.menuIds = [];
        this.$nextTick(() => {
          if (this.$refs.roleTree) {
            this.$refs.roleTree.setCheckedKeys([]);
          }
        });
      }
    },
    getSelectedNode(node) {
      roleMenuTreeSelected({
        roleId: node,
      }).then((res) => {
        if (res.code == 0) {
          this.menuIds = res.data;
          this.$nextTick(() => {
            if (this.$refs.roleTree) {
              this.$refs.roleTree.setCheckedKeys(this.menuIds);
            }
          });
        }
      });
    },
    // 递归处理树形数据，添加label字段
    processTreeData(data) {
      if (!Array.isArray(data)) {
        return [];
      }

      return data.map((item) => {
        // 创建新对象，避免直接修改原始数据
        const processedItem = {
          ...item,
          label: item.menuName || item.label || "", // 使用menuName作为label
        };

        // 如果有子节点，递归处理
        if (processedItem.children && processedItem.children.length > 0) {
          processedItem.children = this.processTreeData(processedItem.children);
        }

        return processedItem;
      });
    },

    handleClose() {
      this.dialogVisible = false; // 关闭弹窗
      this.$emit("close"); // 发送关闭事件给父组件
    },

    //  处理展开/折叠状态变化
    handleCollapseChange(val) {
      if (val) {
        // 展开所有节点
        this.expandAllNodes(true);
      } else {
        // 折叠所有节点
        this.expandAllNodes(false);
      }
    },

    //  控制所有节点展开/折叠
    expandAllNodes(expand) {
      const nodes = this.$refs.roleTree.store._getAllNodes();
      nodes.forEach((node) => {
        node.expanded = expand;
      });
    },

    append(data) {
      const newChild = { id: id++, label: "testtest", children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },

    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.append(data)}
            >
              Append
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              Delete
            </el-button>
          </span>
        </span>
      );
    },
    // 根据节点层级返回对应的图标
    getNodeIcon(node) {
      // 获取节点层级，根节点层级为1

      // 第一层级（根节点）使用 fold 图标
      if (node.childNodes && node.childNodes.length > 0) {
        return "fold";
      } else {
        // 第二层级及以后使用 file 图标
        return "file";
      }
    },
    // 新增方法: 处理全选/取消全选状态变化
    handleCheckedChange(val) {
      if (val) {
        // 全选所有节点
        this.checkAllNodes(true);
      } else {
        // 取消全选所有节点
        this.checkAllNodes(false);
      }
    },

    // 新增方法: 控制所有节点选中/取消选中
    checkAllNodes(checked) {
      if (checked) {
        // 获取所有节点并全部选中
        const allNodes = this.$refs.roleTree.store._getAllNodes();
        const allKeys = allNodes.map((node) => node.data.menuId);
        this.$refs.roleTree.setCheckedKeys(allKeys);
      } else {
        // 清空所有选中
        this.$refs.roleTree.setCheckedKeys([]);
      }
    },
    checkNodes(valObj, valArray) {
      this.menuIds = valArray.checkedKeys;
    },
  },
};
</script>
<style scoped lang="scss">
.dialog-role {
  .dialog-ruleForm {
    width: 80%;
    line-height: 60px;
    margin: 0 auto;
  }
  .menu-permisssion {
    border: 1px solid #dcdfe6;
    padding: 15px;
    border-radius: 4px;
  }
}
</style>
